/* eslint-disable no-undef */
import '../Mixin/adapter-latest.js';

let pcc;
export function initVideo() {
  const config = {
    iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
  };
  const sessionid = 'demo1';
  const pc = new RTCPeerConnection(config);
  pcc = pc;
  console.log(pc);

  const log = msg => {
    console.log('===========打印日志===========', msg);
  };

  // 将ontrack设置为你提供的一个输入RTCTrackEvent对象用于描述新的track将如何使用的方法。这一信息包含了代表新track的MediaStreamTrack对象、
  // RTCRtpReceiver对象、RTCRtpTransceiver对象以及一个MediaStream对象列表，该对象列表表示该track是那个媒体流的一部分。
  pc.ontrack = function(event) {
    console.log('ontrack', event.streams[0]);
    if (event.track.kind == 'video') {
      var el = document.createElement(event.track.kind);
      el.srcObject = event.streams[0];
      el.muted = true;
      el.autoplay = true;
      el.controls = true;
      el.width = 304;
      el.height = 214;
      el.id = 'camVideo';
      document.getElementById('remoteVideos').appendChild(el);
    }
  };

  pc.oniceconnectionstatechange = e => {
    // 用于监视ICE代理的连接状态
    if (pc.iceConnectionState === 'failed' ||
        pc.iceConnectionState === 'disconnected' ||
        pc.iceConnectionState === 'closed') {
      console.log(e);
    }
    log(pc.iceConnectionState);
  };

  // 触发icecandidate事件的首要原因：当获得新的源之后，需要将该源的信息发送给远端信号服务器，并分发至其他端的RTCPeerConnection。
  // 其他RTCPeerConnection通过addIceCandidate()方法将新candidate 中携带的信息，将新的源描述信息添加进它的备选池中；
  pc.onicecandidate = event => {
    if (event.candidate == null) {
      document.getElementById('localSessionDescription').value = btoa(pc.localDescription.sdp);
      $.post('http://10.10.27.181:8083/recive', { 'suuid': sessionid, 'data': btoa(pc.localDescription.sdp) }, function(res) {
        console.log('=======remoteSessionDescription==========================data', res);
        document.getElementById('remoteSessionDescription').value = res;
        window.startSession();
      });
    }
  };

  pc.createOffer({ offerToReceiveVideo: true, offerToReceiveAudio: true }).then(d => pc.setLocalDescription(d)).catch(log);

  window.startSession = () => {
    const sd = document.getElementById('remoteSessionDescription').value;
    if (sd === '') {
      console.log('Session Description must not be empty');
    }
    try {
      // setRemoteDescription改变与连接相关的描述，该描述主要是描述有些关于连接的属性，例如对端使用的解码器。连接受此更改影响，并且必须能够支持旧的和新的描述。
      // 方法带三个参数，RTCSessionDescription 对象用于设置，然后是更改成功的回调方法，一个是更改失败的回调方法。
      pc.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp: atob(sd) }));
    } catch (e) {
      console.log(e);
    }
  };
}

// 关闭RTCPeerConnection
export function closeVideo() {
  console.log('关闭RTCPeerConnection', pcc);
  document.getElementById('remoteVideos').innerHTML = '';
  document.getElementById('remoteSessionDescription').value = '';
  document.getElementById('localSessionDescription').value = '';
  pcc.close();
}
